{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2025-02-26T11:06:42.361841Z",
     "start_time": "2025-02-26T11:06:40.092729Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": "(device(type='cpu'), device(type='cuda'), device(type='cuda', index=1))"
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import torch\n",
    "from torch import nn\n",
    "\n",
    "torch.device('cpu'), torch.device('cuda'), torch.device('cuda:1')"
   ]
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "data": {
      "text/plain": "False"
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "torch.device('cuda') == torch.device('cuda:0')"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2025-02-26T11:09:12.450312Z",
     "start_time": "2025-02-26T11:09:12.432319Z"
    }
   },
   "id": "ba2e861b76694c72",
   "execution_count": 2
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "data": {
      "text/plain": "1"
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "torch.cuda.device_count()"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2025-02-26T11:09:30.375719Z",
     "start_time": "2025-02-26T11:09:30.301727Z"
    }
   },
   "id": "7db37b8eb478f6d7",
   "execution_count": 3
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "data": {
      "text/plain": "(device(type='cuda', index=0),\n device(type='cpu'),\n [device(type='cuda', index=0)])"
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def try_gpu(i=0):  #@save\n",
    "    \"\"\"如果存在，则返回gpu(i)，否则返回cpu()\"\"\"\n",
    "    if torch.cuda.device_count() >= i + 1:\n",
    "        return torch.device(f'cuda:{i}')\n",
    "    return torch.device('cpu')\n",
    "\n",
    "def try_all_gpus():  #@save\n",
    "    \"\"\"返回所有可用的GPU，如果没有GPU，则返回[cpu(),]\"\"\"\n",
    "    devices = [torch.device(f'cuda:{i}')\n",
    "             for i in range(torch.cuda.device_count())]\n",
    "    return devices if devices else [torch.device('cpu')]\n",
    "\n",
    "try_gpu(), try_gpu(10), try_all_gpus()"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2025-02-26T11:10:28.712402Z",
     "start_time": "2025-02-26T11:10:28.683413Z"
    }
   },
   "id": "35a196ebd9858ade",
   "execution_count": 4
  },
  {
   "cell_type": "markdown",
   "source": [
    "# 5.6.2. 张量与GPU"
   ],
   "metadata": {
    "collapsed": false
   },
   "id": "7c4869c5b802bd66"
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "data": {
      "text/plain": "device(type='cpu')"
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x = torch.tensor([1, 2, 3])\n",
    "x.device"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2025-02-26T11:10:51.647859Z",
     "start_time": "2025-02-26T11:10:51.632861Z"
    }
   },
   "id": "8ed6ab7e1b535810",
   "execution_count": 5
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "data": {
      "text/plain": "tensor([[1., 1., 1.],\n        [1., 1., 1.]], device='cuda:0')"
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X = torch.ones(2, 3, device=try_gpu())\n",
    "X"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2025-02-26T11:11:03.603493Z",
     "start_time": "2025-02-26T11:11:02.904226Z"
    }
   },
   "id": "91abb59c1bb16fdd",
   "execution_count": 6
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "data": {
      "text/plain": "(tensor([[0.2148, 0.7241, 0.1142],\n         [0.8084, 0.9796, 0.0858]]),\n device(type='cpu'))"
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "Y = torch.rand(2, 3, device=try_gpu(1))\n",
    "Y, Y.device"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2025-02-26T11:11:53.792203Z",
     "start_time": "2025-02-26T11:11:53.757237Z"
    }
   },
   "id": "334b2b80c6c2ca5f",
   "execution_count": 8
  },
  {
   "cell_type": "markdown",
   "source": [
    "# 5.6.2.2. 复制\n",
    "如果我们要计算X + Y，我们需要决定在哪里执行这个操作。 例如，如 图5.6.1所示， 我们可以将X传输到第二个GPU并在那里执行操作。 不要简单地X加上Y，因为这会导致异常， 运行时引擎不知道该怎么做：它在同一设备上找不到数据会导致失败。 由于Y位于第二个GPU上，所以我们需要将X移到那里， 然后才能执行相加运算"
   ],
   "metadata": {
    "collapsed": false
   },
   "id": "d483a600440a15ef"
  },
  {
   "cell_type": "code",
   "outputs": [],
   "source": [
    "Z = X.cuda(1)\n",
    "print(X)\n",
    "print(Z)"
   ],
   "metadata": {
    "collapsed": false
   },
   "id": "9ac1fb0f5d119961"
  },
  {
   "cell_type": "markdown",
   "source": [
    "假设变量Z已经存在于第二个GPU上。 如果我们还是调用Z.cuda(1)会发生什么？ 它将返回Z，而不会复制并分配新内存。"
   ],
   "metadata": {
    "collapsed": false
   },
   "id": "d4a4868dc38a0716"
  },
  {
   "cell_type": "code",
   "outputs": [],
   "source": [
    "Z.cuda(1) is Z # True"
   ],
   "metadata": {
    "collapsed": false
   },
   "id": "afa00bb4240d78f1"
  },
  {
   "cell_type": "markdown",
   "source": [
    "# 5.6.3. 神经网络与GPU"
   ],
   "metadata": {
    "collapsed": false
   },
   "id": "110726b8a3ae53bd"
  },
  {
   "cell_type": "code",
   "outputs": [],
   "source": [
    "net = nn.Sequential(nn.Linear(3, 1))\n",
    "net = net.to(device=try_gpu())"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2025-02-26T11:13:29.699403Z",
     "start_time": "2025-02-26T11:13:29.674403Z"
    }
   },
   "id": "382aff95acabc1ec",
   "execution_count": 9
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "data": {
      "text/plain": "tensor([[0.4815],\n        [0.4815]], device='cuda:0', grad_fn=<AddmmBackward0>)"
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "net(X)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2025-02-26T11:13:34.890990Z",
     "start_time": "2025-02-26T11:13:34.702905Z"
    }
   },
   "id": "a77d6f78bfc0322f",
   "execution_count": 10
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "data": {
      "text/plain": "device(type='cuda', index=0)"
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "net[0].weight.data.device"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2025-02-26T11:13:39.696331Z",
     "start_time": "2025-02-26T11:13:39.675294Z"
    }
   },
   "id": "d75845cf8ef231f9",
   "execution_count": 11
  },
  {
   "cell_type": "code",
   "outputs": [],
   "source": [],
   "metadata": {
    "collapsed": false
   },
   "id": "bc78f7e17a05cd0b"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
